<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\room;


use app\common\model\room\RoomApartment;
use app\common\logic\BaseLogic;
use app\common\model\room\RoomApartmentDevice;
use app\common\model\room\RoomApartmentUserRecords;
use app\common\model\user\User;
use app\common\service\ConfigService;
use think\facade\Config;
use think\facade\Db;


/**
 * 公寓房间管理逻辑
 * Class RoomApartmentLogic
 * @package app\adminapi\logic\room
 */
class RoomApartmentLogic extends BaseLogic {


    /**
     * @notes 添加公寓房间管理
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public static function add(array $params): bool {
        Db::startTrans();
        try {
//            $user_ids = $params['user_ids'];
            $user_ids = [];
            $passwordSalt = Config::get('project.unique_identification');
            $password = create_password("123456", $passwordSalt);
            $avatar = ConfigService::get('default_image', 'user_avatar');

            foreach ($params['user'] as $k => $v) {
                if (empty($v['user_name'])) {
                    $user_ids[] = 0;
                    $params['user'][$k]['user_id'] = 0;
                    continue;
                }

                $user = User::where([
                    "cid" => $params['cid'],
                    "real_name" => trim($v['user_name']),
                    "mobile" => trim($v['user_mobile']),
                ])->find();

                if ($user) {
                    $user_id = $user['id'];
                } else {
                    $sn = User::createUserSn();
                    $user_id = User::create([
                        "cid" => $params['cid'],
                        "did" => 0,
                        "real_name" => trim($v['user_name']),
                        "mobile" => trim($v['user_mobile']),
                        "nickname" => trim($v['user_name']),
                        "sn" => $sn,
                        "account" => $sn,
                        "password" => $password,
                        "avatar" => $avatar,
                        "channel" => 4,
                        "create_time" => time(),
                        "update_time" => time(),
                    ])->getLastInsID();
                }

                $user_ids[] = $user_id ?? 0;
                $params['user'][$k]['user_id'] = $user_id ?? 0;
            }

            $params['water_consumption'] = $params['water_consumption'] ?? 0;
            $params['water_price'] = $params['water_price'] ?? 0;
            $params['water_fee'] = 1 * $params['water_consumption'] * $params['water_price'];

            $new_create = [
                'cid' => $params['cid'],
                'bid' => $params['bid'],
                'name' => $params['name'],
                'status' => $params['status'],
                'add_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s"),
                'device_total' => $params['device_total'],
                // 'device_fee_time' => $params['device_fee_time'],
                'user_ids' => implode(",", $user_ids),
                'user_count' => count($user_ids),
                'address' => $params['address'],
                'lift_type' => $params['lift_type'],
                'lift_fee' => $params['lift_fee'],
                'second_pressure_fee' => $params['second_pressure_fee'],
                'water_consumption' => $params['water_consumption'],
                'water_price' => $params['water_price'],
                'water_fee' => $params['water_fee'],
                'sort' => $params['sort'] ?? 10000,
            ];
            $rid = RoomApartment::create($new_create)->getLastInsID();

//            $sdc = ConfigService::get('room_apartment', 's_device_coefficient');
//            $sdp = ConfigService::get('room_apartment', 's_device_price');
            $ddc = ConfigService::get('room_apartment', 'd_device_coefficient');
            $ddp = ConfigService::get('room_apartment', 'd_device_price');

            $device_create = [
                "cid" => $new_create['cid'],
                "bid" => $new_create['bid'],
                "sort" => $new_create['sort'],
                "rid" => $rid,
                'add_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s"),
                "status" => 1,
                "room_master" => 1, // 主房间
                "device_type" => 2, // 默认电表
                "coefficient" => $ddc, // 系数
                "price" => $ddp, // 水电价
            ];
            RoomApartmentDevice::create($device_create);
            // $device_id = RoomApartmentDevice::getLastInsID();

            RoomApartmentUserRecords::where([
                "room_apartment_id" => $rid,
            ])->whereNotIn("user_id", $user_ids)->delete();
            $raur_user_ids = RoomApartmentUserRecords::where([
                "room_apartment_id" => $rid,
            ])->column("user_id");
            foreach ($params['user'] as $user_val) {
                if ($user_val['user_id'] <= 0) {
                    continue;
                }
                if (!in_array($user_val['user_id'], $raur_user_ids)) {
                    RoomApartmentUserRecords::create([
                        "room_apartment_id" => $rid,
                        "user_name" => trim($user_val['user_name']),
                        "user_mobile" => trim($user_val['user_mobile']),
                        "user_id" => $user_val['user_id'],
                    ]);
                }
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑公寓房间管理
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public static function edit(array $params): bool {
        Db::startTrans();
        try {
//            $user_ids = $params['user_ids'];
            $user_ids = [];
            $params['water_consumption'] = $params['water_consumption'] ?? 0;
            $params['water_price'] = $params['water_price'] ?? 0;
            $params['water_fee'] = 1 * $params['water_consumption'] * $params['water_price'];

            $passwordSalt = Config::get('project.unique_identification');
            $password = create_password("123456", $passwordSalt);
            $avatar = ConfigService::get('default_image', 'user_avatar');

            foreach ($params['user'] as $k => $v) {
                if (empty($v['user_name'])) {
                    $user_ids[] = 0;
                    $params['user'][$k]['user_id'] = 0;
                    continue;
                }

                $user = User::where([
                    "cid" => $params['cid'],
                    "real_name" => trim($v['user_name']),
                    "mobile" => trim($v['user_mobile']),
                ])->find();

                if ($user) {
                    $user_id = $user['id'];
                } else {
                    $sn = User::createUserSn();
                    $user_id = User::create([
                        "cid" => $params['cid'],
                        "did" => 0,
                        "real_name" => trim($v['user_name']),
                        "mobile" => trim($v['user_mobile']),
                        "nickname" => trim($v['user_name']),
                        "sn" => $sn,
                        "account" => $sn,
                        "password" => $password,
                        "avatar" => $avatar,
                        "channel" => 4,
                        "create_time" => time(),
                        "update_time" => time(),
                    ])->getLastInsID();
                }

                $user_ids[] = $user_id ?? 0;
                $params['user'][$k]['user_id'] = $user_id ?? 0;
            }

            $update = [
                'cid' => $params['cid'],
                'bid' => $params['bid'],
                'name' => $params['name'],
                'status' => $params['status'],
                'update_time' => date("Y-m-d H:i:s"),
                'device_total' => $params['device_total'],
//                'device_fee_time' => $params['device_fee_time'],
                'sort' => is_numeric($params['sort']) ? $params['sort'] : 100,
                'user_ids' => implode(",", $user_ids),

                'user_count' => count($user_ids),
                'address' => $params['address'],
                'lift_type' => $params['lift_type'],
                'lift_fee' => $params['lift_fee'],
                'second_pressure_fee' => $params['second_pressure_fee'],
                'water_consumption' => $params['water_consumption'],
                'water_price' => $params['water_price'],
                'water_fee' => $params['water_fee'],
            ];
            RoomApartment::where('id', $params['id'])->update($update);

            $device_update = [
                'cid' => $update['cid'],
                'bid' => $update['bid'],
                'update_time' => date("Y-m-d H:i:s"),
                'sort' => $update['sort'],
            ];
            RoomApartmentDevice::where('rid', $params['id'])->update($device_update);

            RoomApartmentUserRecords::where([
                "room_apartment_id" => $params['id'],
            ])->whereNotIn("user_id", $user_ids)->delete();
            $raur_user_ids = RoomApartmentUserRecords::where([
                "room_apartment_id" => $params['id'],
            ])->column("user_id");
            foreach ($params['user'] as $user_val) {
                if ($user_ids['user_id'] <= 0) {
                    continue;
                }
                if (!in_array($user_val['user_id'], $raur_user_ids)) {
                    RoomApartmentUserRecords::create([
                        "room_apartment_id" => $params['id'],
                        "user_name" => trim($user_val['user_name']),
                        "user_mobile" => trim($user_val['user_mobile']),
                        "user_id" => $user_val['user_id'],
                    ]);
                }
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除公寓房间管理
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public static function delete(array $params): bool {
        RoomApartmentDevice::whereIn("rid", $params['id'])->delete();
        RoomApartmentUserRecords::where("room_apartment_id", $params['id'])->delete();
        return RoomApartment::destroy($params['id']);
    }


    /**
     * @notes 获取公寓房间管理详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public static function detail($params): array {
        return RoomApartment::findOrEmpty($params['id'])->toArray();
    }


    public static function setSave(array $params): bool {
        Db::startTrans();
        $params['water_consumption'] = $params['water_consumption'] ?? 0;
        $params['water_price'] = $params['water_price'] ?? 0;
        $params['water_fee'] = 1 * $params['water_consumption'] * $params['water_price'];
        try {
            RoomApartment::where('id', $params['id'])->update([
                'update_time' => date("Y-m-d H:i:s"),
                'water_consumption' => $params['water_consumption'],
                'water_price' => $params['water_price'],
                'water_fee' => $params['water_fee'] ?? 0,
            ]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


}

